package com.example.onlineeducation.utils


import androidx.recyclerview.widget.RecyclerView
import com.example.onlineeducation.adapter.ProblemAdapter
import com.example.onlineeducation.data.entity.ProblemEntity
import com.yc.jetpacklib.extension.showToast

/**
 * Creator: yc
 * Date: 2022/4/22 16:42
 * UseDes:
 */
class ProblemAdapterUtil {

    private lateinit var mRecyclerView: RecyclerView

    private val mAdapter: ProblemAdapter = ProblemAdapter()
    private var mCurrentPosition = 0
    var mProblemNumCall: ((currentPosition: Int, itemCount: Int) -> Unit)? = null

    fun initRecyclerView(rv: RecyclerView) {
        mRecyclerView = rv
        mRecyclerView.adapter = mAdapter
    }

    fun reset() {
        mCurrentPosition = 0
        mRecyclerView.scrollToPosition(mCurrentPosition)
        mProblemNumCall?.invoke(mCurrentPosition, mAdapter.itemCount)
    }

    fun before() {
        if (mCurrentPosition > 0) {
            mRecyclerView.scrollToPosition(--mCurrentPosition)
            mProblemNumCall?.invoke(mCurrentPosition, mAdapter.itemCount)
        }
    }

    fun next() {
        val nextPosition = mCurrentPosition + 1
        if (nextPosition < mAdapter.itemCount) {
            if (mAdapter.checkProblemSelect(mCurrentPosition)) {
                mCurrentPosition = nextPosition
                mRecyclerView.scrollToPosition(mCurrentPosition)
                mProblemNumCall?.invoke(mCurrentPosition, mAdapter.itemCount)
            } else {
                mRecyclerView.context.showToast("请选择答案")
            }
        }
    }

    /**
     * 检测此题是否有选中
     * @param position Int
     * @return Boolean
     */
    fun checkFinishCall(black: () -> Unit) {
        if (mAdapter.checkProblemSelect(mAdapter.itemCount - 1)) {
            black.invoke()
        } else {
            mRecyclerView.context.showToast("请选择答案")
        }
    }

    fun addAll(newData: List<ProblemEntity>?) {
        mAdapter.addAll(newData)
        mCurrentPosition = 0
        mProblemNumCall?.invoke(mCurrentPosition, mAdapter.itemCount)
    }

    fun getData() = mAdapter.getData()
}